<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .box{
            position: absolute;
            top: 50px;
            left: 50px;
            width: 200px;
            height: 200px;
            background-color: pink;
            opacity: 1;
        }
    </style>
</head>
<body>
    <div class="box"></div>

    <script>
        var box = document.querySelector('.box');

        box.onclick = function () {
            // animation(this, 'width', 421);
            animation(this, 'opacity', .3)
        }

        // 动画封装
        function animation (el, styleName, styleTarget) {
            var nowStyle = parseInt(window.getComputedStyle(el, null)[styleName]);
            // 清除定时器
            if (el.timer) {
                clearInterval(el.timer)
            }
            // 起始样式和目标样式相同，直接返回
            if(nowStyle === styleTarget) {
                return
            }
            // 样式为z-index时
            if (styleName === 'zIndex') {
                el.style.zIndex = styleTarget;
                return
            }
            if (styleName === 'opacity') {
                nowStyle *= 100;
                styleTarget *= 100
            }
            // 设置定时器
            el.timer = setInterval(function () {
                var step = (styleTarget-nowStyle) / 10;
                // 修正步长
                if (Math.abs(step) < 1) {
                    step = step > 0 ? 1 : Math.floor(step)
                }
                // 取整
                nowStyle = Math.floor(step + nowStyle);
                if (styleName === 'opacity') {
                    box.style[styleName] = nowStyle/100;                  
                } else {
                    box.style[styleName] = nowStyle + 'px';
                }
                // 终止条件
                if (nowStyle === styleTarget) {
                    clearInterval(el.timer);
                    el.timer = null;
                    console.log('stop...');
                }
            }, 1000/60)
        } 
    </script>
</body>
</html>